package com.ucar.training.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author XiongMM
 * @date 2019/7/26 15:03
 * @description
 */
public class NameFilter implements Filter {

    private FilterConfig filterConfig;
    private String[] blackList;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.blackList = this.filterConfig.getInitParameter("blacklist").split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String userName=servletRequest.getParameter("username");
        if(userName != null){
            userName=new String(userName.getBytes("ISO-8859-1"),"UTF-8");
        }

        if(userName!=null && isContainName(userName)){
            servletResponse.setContentType("text/html;charset=UTF-8");
            PrintWriter out=servletResponse.getWriter();
            out.print("<html><body>");
            out.print("<h1>对不起，"+userName+"，你没有权限登录</h1>");
            out.print("</body></html>");
            out.flush();
            return;
        }
        long before=System.currentTimeMillis();
        this.filterConfig.getServletContext().log("NoteFilter:before call chain.doFilter()");
        filterChain.doFilter(servletRequest, servletResponse);
        this.filterConfig.getServletContext().log("NoteFilter:after call chain.doFilter()");
        long after=System.currentTimeMillis();
        String url="";

        if(servletRequest instanceof HttpServletRequest) {
            url = ((HttpServletRequest) servletRequest).getRequestURI();
        }
        this.filterConfig.getServletContext().log("NameFilter:"+url+":"+(after-before)+"ms");
}

    @Override
    public void destroy() {

    }

    private boolean isContainName(String name){
        for(String userName : this.blackList){
            if(userName.equals(name)){
                return true;
            }
        }
        return false;
    }
}
